"""
自定义装饰器模块
"""
from functools import wraps
from flask import flash, redirect, url_for, abort, request
from flask_login import current_user
from app.models.role import Permission


def permission_required(permission):
    """
    权限检查装饰器
    :param permission: 需要的权限
    :return: 装饰器函数
    """
    def decorator(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            if not current_user.is_authenticated:
                flash('请先登录', 'warning')
                return redirect(url_for('auth.login', next=request.url))
            
            if not current_user.can(permission):
                flash('您没有权限访问此页面', 'danger')
                return redirect(url_for('main.index'))
            
            return f(*args, **kwargs)
        return decorated_function
    return decorator


def admin_required(f):
    """
    管理员权限检查装饰器
    """
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if not current_user.is_authenticated:
            flash('请先登录', 'warning')
            return redirect(url_for('auth.login', next=request.url))
        
        if not current_user.is_administrator():
            flash('您需要管理员权限才能访问此页面', 'danger')
            return redirect(url_for('main.index'))
        
        return f(*args, **kwargs)
    return decorated_function


def role_required(*role_names):
    """
    角色检查装饰器
    :param role_names: 需要的角色名称列表
    :return: 装饰器函数
    """
    def decorator(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            if not current_user.is_authenticated:
                flash('请先登录', 'warning')
                return redirect(url_for('auth.login', next=request.url))
            
            user_roles = {role.name for role in current_user.roles}
            required_roles = set(role_names)
            
            if not user_roles.intersection(required_roles):
                flash('您没有合适的角色权限访问此页面', 'danger')
                return redirect(url_for('main.index'))
            
            return f(*args, **kwargs)
        return decorated_function
    return decorator


def anonymous_required(f):
    """
    匿名访问装饰器（已登录用户不能访问）
    """
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if current_user.is_authenticated:
            flash('您已经登录，不能访问此页面', 'info')
            return redirect(url_for('main.index'))
        
        return f(*args, **kwargs)
    return decorated_function


def confirmed_required(f):
    """
    邮箱验证装饰器
    """
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if not current_user.is_authenticated:
            flash('请先登录', 'warning')
            return redirect(url_for('auth.login', next=request.url))
        
        if not current_user.confirmed:
            flash('请先验证您的邮箱', 'warning')
            return redirect(url_for('auth.unconfirmed'))
        
        return f(*args, **kwargs)
    return decorated_function